//
//  ShopTableViewController.swift
//  BookStore
//
//  Created by JinYuXin on 2022/5/11.
//

import UIKit

class ShopTableViewController: UITableViewController {

    let defaults = UserDefaults.standard
    var bookids=[String]()
    var booklists=[[String:String]]()
    var userid:String=""
    var totalprice:String=""
    
    @IBOutlet weak var baritem: UITabBarItem!
    override func viewDidLoad() {
        super.viewDidLoad()
        let xib = UINib(nibName: "BookTableViewCell", bundle: nil)
        tableView.register(xib, forCellReuseIdentifier: "shopcell")
        tableView.rowHeight = 170

    }
    override func viewWillAppear(_ animated: Bool) {
        getBookInfo()
        baritem.badgeValue=String(bookids.count)
        tableView.reloadData()
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return bookids.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "shopcell", for: indexPath) as! BookTableViewCell
        
        cell.bookTitle.text = booklists[indexPath.row]["title"]
        cell.bookPrice.text = booklists[indexPath.row]["price"]
        cell.bookImage.downloadAsyncFrom(url: booklists[indexPath.row]["pic"]!)
        return cell
        
    }

    
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            let id = bookids[indexPath.row]
            bookids.remove(at: indexPath.row)
            booklists.remove(at: indexPath.row)
            //print(bookids.count)
            baritem.badgeValue=String(bookids.count)
            
            UserShopCarTable.deleteUserShopCar(id, userid)
            UserShopCarTable.GetUserShopCar()
            tableView.beginUpdates()
            tableView.deleteRows(at: [indexPath], with: .fade)
            tableView.endUpdates()
        }
    }
    
    
    func getBookInfo()
    {
        getBookId()
        booklists=[]
        for book in bookids{
            let queryResult = BookTable.getBookInfo(book)
            let a = queryResult as! [[String:String]]
            let info = a[0]
            booklists.append(info)
        }
    }
    func getBookId()
    {
        let user = defaults.string(forKey: "userName")!
        let queryuser = UserTable.getUserId(user)
        userid = String(queryuser![0]["id"]! as! Int)
        let queryuserid = UserShopCarTable.getBookId(userid)
        let userid = queryuserid as! [[String:String]]
        bookids=[]
        for book in userid{
            bookids.append(book["bookid"]!)
        }
    }
    func getTotalPrice()
    {
        var total:Float = 0
        for row in booklists{
            let price = Float(row["price"]!)!
            total = total + price
        }
        totalprice = String(total)
    }

    @IBAction func payButtonPressed(_ sender: UIButton) {
        getTotalPrice()
        let controller:PayViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "pay") as! PayViewController
        controller.price = totalprice
        controller.userid = userid
        controller.bookids = bookids
        controller.booknum = String(bookids.count)
        //self.show(controller, sender: self)
        UIApplication.shared.windows[0].rootViewController = controller
        //self.present(controller, animated: true, completion: nil)
    }
    

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
